<template>
  <div class="users-container">
    <div class="page-header">
      <h2>用户管理</h2>
      <el-button type="primary" @click="handleAddUser" size="default">
        <el-icon><component is="i-plus" /></el-icon>
        添加用户
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="部门">
          <el-select
            v-model="searchForm.department_id"
            placeholder="请选择部门"
            clearable
            size="small"
          >
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.is_active"
            placeholder="请选择状态"
            clearable
            size="small"
          >
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" size="small">
            <el-icon><component is="i-search" /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch" size="small">
            <el-icon><component is="i-refresh-left" /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户表格 -->
    <el-card class="users-table-card" shadow="hover">
      <el-table
        :data="usersData"
        style="width: 100%"
        border
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="id" label="ID" width="80" fixed />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="full_name" label="姓名" width="150" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="department_name" label="部门" width="150">
          <template #default="{ row }">
            <el-tag size="small">{{ row.department_name || "-" }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="is_active" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.is_active"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleStatusChange(row)"
              :loading="statusChangingId === row.id"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEditUser(row)"
              :disabled="editingId === row.id"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteUser(row)"
              :disabled="deletingId === row.id"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      width="600px"
      destroy-on-close
    >
      <el-form
        :model="userForm"
        :rules="userRules"
        ref="userFormRef"
        label-width="100px"
        class="user-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userForm.username"
            placeholder="请输入用户名"
            :disabled="dialogType === 'edit'"
          />
        </el-form-item>

        <el-form-item label="姓名" prop="full_name">
          <el-input v-model="userForm.full_name" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item v-if="dialogType === 'add'" label="密码" prop="password">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="部门" prop="department_id">
          <el-select
            v-model="userForm.department_id"
            placeholder="请选择部门"
            clearable
          >
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="is_active">
          <el-switch
            v-model="userForm.is_active"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="dialogLoading"
          >
            {{ dialogLoading ? "提交中..." : "确定" }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import service from '@/utils/request';

export default {
  name: "Users",
  setup() {
    const loading = ref(false);
    const dialogVisible = ref(false);
    const dialogType = ref("add"); // 'add' or 'edit'
    const dialogLoading = ref(false);
    const userFormRef = ref(null);
    const editingId = ref(null);
    const deletingId = ref(null);
    const statusChangingId = ref(null);

    // 搜索表单
    const searchForm = reactive({
      username: "",
      department_id: "",
      is_active: "",
    });

    // 分页
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0,
    });

    // 用户表单
    const userForm = reactive({
      id: "",
      username: "",
      full_name: "",
      email: "",
      password: "",
      department_id: "",
      is_active: true,
    });

    // 表单验证规则
    const userRules = {
      username: [
        { required: true, message: "请输入用户名", trigger: "blur" },
        {
          min: 2,
          max: 20,
          message: "用户名长度在 2 到 20 个字符",
          trigger: "blur",
        },
      ],
      full_name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
      email: [
        { required: true, message: "请输入邮箱", trigger: "blur" },
        { type: "email", message: "请输入有效的邮箱地址", trigger: "blur" },
      ],
      password: [
        { required: true, message: "请输入密码", trigger: "blur" },
        { min: 6, message: "密码长度不能少于6个字符", trigger: "blur" },
      ],
    };

    // 模拟部门数据
    const departments = ref([
      { id: 1, name: "技术部" },
      { id: 2, name: "运营部" },
      { id: 3, name: "研发部" },
      { id: 4, name: "测试部" },
    ]);

    // 用户数据
    const usersData = ref([]);

    // 初始化
    onMounted(() => {
      fetchUsers();
    });

    // 获取用户列表
    const fetchUsers = async () => {
      loading.value = true;
      try {
        // 从后端API获取用户数据
        const response = await service.get("/users", {
          params: {
            page: pagination.currentPage,
            page_size: pagination.pageSize,
            username: searchForm.username || undefined,
            department_id: searchForm.department_id || undefined,
            is_active:
              searchForm.is_active !== "" ? searchForm.is_active : undefined,
          }
        });
        console.log("response:", response);
        if (response.code === 200) {
          // 添加department_name字段，通过部门ID查找部门名称
          usersData.value = response.data.items.map((user) => {
            const department = departments.value.find(
              (dept) => dept.id === user.department_id
            );
            return {
              ...user,
              department_name: department ? department.name : "",
              full_name: user.email.split("@")[0], // 使用邮箱前缀作为full_name
            };
          });
          pagination.total = response.data.total;
        } else {
          ElMessage.error(response.message || "获取用户列表失败");
        }
      } catch (error) {
        console.error("获取用户列表失败:", error);
        ElMessage.error(error.response?.message || "获取用户列表失败");
      } finally {
        loading.value = false;
      }
    };

    // 搜索
    const handleSearch = () => {
      pagination.currentPage = 1;
      fetchUsers();
    };

    // 重置搜索
    const resetSearch = () => {
      Object.keys(searchForm).forEach((key) => {
        searchForm[key] = "";
      });
      pagination.currentPage = 1;
      fetchUsers();
    };

    // 分页处理
    const handleSizeChange = (size) => {
      pagination.pageSize = size;
      fetchUsers();
    };

    const handleCurrentChange = (current) => {
      pagination.currentPage = current;
      fetchUsers();
    };

    // 打开添加用户对话框
    const handleAddUser = () => {
      dialogType.value = "add";
      resetUserForm();
      dialogVisible.value = true;
    };

    // 打开编辑用户对话框
    const handleEditUser = (row) => {
      dialogType.value = "edit";
      editingId.value = row.id;
      // 复制数据
      Object.assign(userForm, row);
      dialogVisible.value = true;
    };

    // 删除用户
    const handleDeleteUser = (row) => {
      ElMessageBox.confirm(`确定要删除用户「${row.username}」吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          deletingId.value = row.id;
          try {
            const response = await service.delete(`/users/${row.id}`);

            if (response.data.code === 200) {
              ElMessage.success("删除成功");
              fetchUsers();
            } else {
              ElMessage.error(response.data.message || "删除用户失败");
            }
          } catch (error) {
            console.error("删除用户失败:", error);
            ElMessage.error(error.response?.data?.message || "删除失败");
          } finally {
            deletingId.value = null;
          }
        })
        .catch(() => {
          // 取消删除
          ElMessage.info("已取消删除");
        });
    };

    // 修改用户状态
    const handleStatusChange = async (row) => {
      statusChangingId.value = row.id;
      try {
        // 实际项目中这里应该调用后端API
        // await axios.patch(`/users/${row.id}/status`, {
        //   is_active: row.is_active
        // })

        // 模拟API调用
        setTimeout(() => {
          ElMessage.success(row.is_active ? "用户已启用" : "用户已禁用");
        }, 300);
      } catch (error) {
        console.error("修改用户状态失败:", error);
        row.is_active = !row.is_active; // 回滚状态
        ElMessage.error("操作失败");
      } finally {
        statusChangingId.value = null;
      }
    };

    // 重置用户表单
    const resetUserForm = () => {
      if (userFormRef.value) {
        userFormRef.value.resetFields();
      }
      Object.assign(userForm, {
        id: "",
        username: "",
        full_name: "",
        email: "",
        password: "",
        department_id: "",
        is_active: true,
      });
    };

    // 提交表单
    const handleSubmit = async () => {
      userFormRef.value.validate(async (valid) => {
        if (valid) {
          dialogLoading.value = true;
          try {
            if (dialogType.value === "add") {
              // 添加用户
              const response = await service.post(
                "/users",
                {
                  username: userForm.username,
                  password: userForm.password,
                  email: userForm.email,
                  department_id: userForm.department_id,
                  is_active: userForm.is_active,
                }
              );

              if (response.data.code === 200) {
                ElMessage.success("添加成功");
                dialogVisible.value = false;
                fetchUsers();
              } else {
                ElMessage.error(response.data.message || "添加用户失败");
              }
            } else {
              // 更新用户
              const response = await service.put(
                `/users/${editingId.value}`,
                {
                  username: userForm.username,
                  email: userForm.email,
                  department_id: userForm.department_id,
                  is_active: userForm.is_active,
                  password: userForm.password || undefined,
                }
              );

              if (response.data.code === 200) {
                ElMessage.success("更新成功");
                dialogVisible.value = false;
                fetchUsers();
              } else {
                ElMessage.error(response.data.message || "更新用户失败");
              }
            }
          } catch (error) {
            console.error("操作用户失败:", error);
            ElMessage.error(error.response?.data?.message || "操作失败");
          } finally {
            dialogLoading.value = false;
            editingId.value = null;
          }
        }
      });
    };

    return {
      loading,
      dialogVisible,
      dialogType,
      dialogLoading,
      userFormRef,
      searchForm,
      pagination,
      userForm,
      userRules,
      departments,
      usersData,
      editingId,
      deletingId,
      statusChangingId,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleAddUser,
      handleEditUser,
      handleDeleteUser,
      handleStatusChange,
      handleSubmit,
    };
  },
};
</script>

<style scoped>
.users-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: end;
}

.search-form .el-form-item {
  margin-bottom: 15px;
}

.users-table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.user-form .el-form-item {
  margin-bottom: 20px;
}
</style>
